package com.demo.base.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>Description:记录操作日志</p>
 * <p>Author:Gred</p>
 * <p>Date:2017/9/19 19:28</p>
 * <p>version:1.0</p>
 **/
@Aspect
@Component
public class AdminLogAop {

    @Autowired
    private HttpServletRequest request;

    //@描述：方法前处理逻辑
    @Before("@annotation(opLog)")
    public void logInfo() {
        //记录开始时间
        request.setAttribute("startTime", System.currentTimeMillis());
    }

    //@时间：2017/9/19 20:39
    //@描述：方法后处理逻辑
    @After("@annotation(opLog)")
    public void logAfter(){
        long entTime = System.currentTimeMillis();
        Long startTime = (Long) request.getAttribute("startTime");
        System.out.println("方法耗时："+(entTime-startTime)+"ms");
    }

    //@描述：方法环绕处理逻辑
    @Around("@annotation(opLog)")
    public Object logInfoAround(ProceedingJoinPoint pjp) throws Throwable {

        //执行方法，获取方法的返回值获取方法返回值
        Object object =  pjp.proceed();
        //根据返回值，判断判断该方法是否有执行成功
        //获取操作码和操作说明
        Map<String, Object> map = getLogParameter(pjp, request);
        System.out.println("获取到参数："+map.toString());
        //进行操作日志插入记录处理
        System.out.println("插入成功");

        return object;
    }

    /**
     * <p>Description:获取注解中对方法的描述信息 用于Controler层注解</p>
     * <p>Author:Gred</p>
     * <p>Date:2017/9/19 19:57</p>
     * <p>param:joinPoint</p>
     **/
    public static Map<String, Object> getLogParameter(ProceedingJoinPoint pjp, HttpServletRequest request)
            throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        String targetName = pjp.getTarget().getClass().getName();//获取目标类的名称
        String methodName = pjp.getSignature().getName();//获取目标方法名
        Object[] arguments = pjp.getArgs();//返回目标方法的参数
        Class targetClass = Class.forName(targetName);//加载目标类
        Method[] methods = targetClass.getMethods();//获取该目标类的所有方法

        String opName = "";
        String beforeRemark = "";
        String afterRemark = "";
        int opCode = 0;
        //获取注解中参数值【下一步需要根据里面的值来当做参数名 从封装好的map里获取值】
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {//判断方法名是否一致
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {//判断参数个数是否一致
                    opName = method.getAnnotation(opLog.class).opName();
                    opCode = method.getAnnotation(opLog.class).opCode();
                    beforeRemark = method.getAnnotation(opLog.class).beforeRemark();
                    afterRemark = method.getAnnotation(opLog.class).afterRemark();
                    break;
                }
            }
        }

        //将隐射成RequestParam的参数封装一个map=
        Map<String, Object> paramMap = changMap(pjp);
        //根据从注解接口中获取的参数名，在从map获取我们需要的值
        beforeRemark = paramMap.get(beforeRemark) == null ? "" : String.valueOf(paramMap.get(beforeRemark));
        afterRemark = paramMap.get(afterRemark) == null ? "" : String.valueOf(paramMap.get(afterRemark));

        map.put("opCode", opCode);
        map.put("opName", opName);
        map.put("beforeRemark", beforeRemark);
        map.put("afterRemark", afterRemark);

        return map;
    }

    //@描述：从切点中中获取已经映射好的参数,因为不确定request的类型，所以只能够通过映射封装好
    //的参数来获取参数值，参数一定要用方法@RequestParam接收
    private static Map<String, Object> changMap(ProceedingJoinPoint pjp) {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] strings = methodSignature.getParameterNames();//获取该方法所有参数
        Object[] args = pjp.getArgs();
        List<String> list = Arrays.asList(strings);
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < args.length; i++) {
            map.put(list.get(i), args[i]);
        }

        return map;
    }


}
